package cn.fzkj.project.system.controller;

import cn.fzkj.common.constant.UserConstants;
import cn.fzkj.common.utils.SecurityUtils;
import cn.fzkj.framework.security.RegisterBody;
import cn.fzkj.framework.web.controller.BaseController;
import cn.fzkj.framework.web.domain.ResultVO;
import cn.fzkj.project.system.domain.SysUser;
import cn.fzkj.project.system.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class SysRegisterController extends BaseController {

    @Autowired
    private ISysUserService userService;

    @PostMapping("/register")
    public ResultVO register (@RequestBody RegisterBody registerBody) {
        System.out.println(registerBody);
        // 默认普通用户
        Long[] roleIds = new Long[]{2L};
        SysUser user = new SysUser();
        user.setEmail(registerBody.getEmail());
        user.setUserName(registerBody.getUsername());
        user.setPassword(registerBody.getPassword());
        user.setNickName("匿名");
        user.setPhonenumber(registerBody.getPhonenumber());
        user.setRoleIds(roleIds);
        if (UserConstants.NOT_UNIQUE.equals(userService.checkUserNameUnique(user.getUserName())))
        {
            return ResultVO.error("新增用户'" + user.getUserName() + "'失败，登录账号已存在");
        }
        else if (UserConstants.NOT_UNIQUE.equals(userService.checkPhoneUnique(user)))
        {
            return ResultVO.error("新增用户'" + user.getUserName() + "'失败，手机号码已存在");
        }
        else if (UserConstants.NOT_UNIQUE.equals(userService.checkEmailUnique(user)))
        {
            return ResultVO.error("新增用户'" + user.getUserName() + "'失败，邮箱账号已存在");
        }
        user.setCreateBy("自由用户");
        user.setPassword(SecurityUtils.encryptPassword(user.getPassword()));
        return toAjax(userService.insertUser(user));
    }

}
